import * as vscode from 'vscode';
const path = require('path');
const fragment = require('./fragment/index');
const tools = require("./util");


/**
 * 鼠标悬停提示，当鼠标停在package.json的dependencies或者devDependencies时，
 * 自动显示对应包的名称、版本号和许可协议
 * @param {*} document 
 * @param {*} position 
 * @param {*} token 
 */
function provideHover(document: { fileName: any; getText: (arg0: any) => any; getWordRangeAtPosition: (arg0: any) => any; }, position: any, token: any) {
  const fileName = document.fileName;
  const workDir = path.dirname(fileName);
  // 获取正在激活的编辑器窗口区域
  let activeTextEditor = vscode.window.activeTextEditor as any;
  const activeDocument = activeTextEditor.document;
  const word = document.getText(document.getWordRangeAtPosition(position));
  // 1. 获取所有选中行信息
  const selection = activeTextEditor.selection;
  // sample for selection: {"start":{"line":2,"character":0},"end":{"line":2,"character":7},"active":{"line":2,"character":7},"anchor":{"line":2,"character":0}}
  const { start, end } = selection;
  // 当前行文本内容
  const curLineText = activeDocument.lineAt(start.line).text;
  // 当前选中文本内容
  const curText = curLineText.substring(start.character, end.character);

  // tools.showInfo("curText:"+curText);
  if (curText.indexOf("huayou") >= 0) {
    // `* **名称**:呵呵呵呵呵呵 \n* **工作目录**: ${workDir} \n* **单词**: ${word}`
    return new vscode.Hover(`${fragment[curText.trim()]}`);
  }

  if (/\/package\.json$/.test(fileName)) {
      console.log('进入provideHover方法');
      const json = (document as any).getText();
      if (new RegExp(`"(dependencies|devDependencies)":\\s*?\\{[\\s\\S]*?${word.replace(/\//g, '\\/')}[\\s\\S]*?\\}`, 'gm').test(json)) {
          let destPath = `${workDir}/node_modules/${word.replace(/"/g, '')}/package.json`;
          if (fs.existsSync(destPath)) {
              const content = require(destPath);
              console.log('hover已生效');
              // hover内容支持markdown语法
              // return new vscode.Hover(`* **名称**：${content.name}\n* **版本**：${content.version}\n* **许可协议**：${content.license}`);

          }
      }
  }
}

module.exports = function (context: { subscriptions: any[]; }) {
  // 注册鼠标悬停提示
  context.subscriptions.push(vscode.languages.registerHoverProvider('*', {
    provideHover
  }));
};